{
  "cells": [
    {
      "metadata": {
        "id": "wdj9RMfoGPC2"
      },
      "cell_type": "markdown",
      "source": [
        "Colab is making it easier than ever to integrate powerful Generative AI capabilities into your projects. We are launching public preview for a simple and intuitive Python library (google.colab.ai) to access state-of-the-art language models directly within Colab environments. All users have free access to most popular LLMs, while paid users have access to a wider selection of models. This means users can spend less time on configuration and set up and more time bringing their ideas to life. With just a few lines of code, you can now perform a variety of tasks:\n",
        "- Generate text\n",
        "- Translate languages\n",
        "- Write creative content\n",
        "- Categorize text\n",
        "\n",
        "Happy Coding!\n",
        "\n",
        "\n",
        "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googlecolab/colabtools/blob/main/notebooks/Getting_started_with_google_colab_ai.ipynb)"
      ]
    },
    {
      "metadata": {
        "id": "Ucchuu5vV3Jp",
        "outputId": "fb014603-40e1-4b99-e89c-d5eefafd7d0d",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "cell_type": "code",
      "source": [
        "# @title List available models\n",
        "from google.colab import ai\n",
        "\n",
        "ai.list_models()"
      ],
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['google/gemini-2.0-flash',\n",
              " 'google/gemini-2.0-flash-lite',\n",
              " 'google/gemini-2.5-flash',\n",
              " 'google/gemini-2.5-flash-lite',\n",
              " 'google/gemini-2.5-pro',\n",
              " 'google/gemma-3-12b',\n",
              " 'google/gemma-3-1b',\n",
              " 'google/gemma-3-27b',\n",
              " 'google/gemma-3-4b']"
            ]
          },
          "metadata": {},
          "execution_count": 2
        }
      ],
      "execution_count": null
    },
    {
      "metadata": {
        "id": "LjfCGEpzDsD9"
      },
      "cell_type": "markdown",
      "source": [
        "Choosing a Model\n",
        "The model names give you a hint about their capabilities and intended use:\n",
        "\n",
        "Pro: These are the most capable models, ideal for complex reasoning, creative tasks, and detailed analysis.\n",
        "\n",
        "Flash: These models are optimized for high speed and efficiency, making them great for summarization, chat applications, and tasks requiring rapid responses.\n",
        "\n",
        "Gemma: These are lightweight, open-weight models suitable for a variety of text generation tasks and are great for experimentation."
      ]
    },
    {
      "metadata": {
        "id": "R7taibpc7x2l",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "71c9fbea-5765-4159-b765-b77c8b4ab34d"
      },
      "cell_type": "code",
      "source": [
        "# @title Simple batch generation example\n",
        "# Only text-to-text input/output is supported\n",
        "from google.colab import ai\n",
        "\n",
        "response = ai.generate_text(\"What is the capital of France?\")\n",
        "print(response)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The capital of France is **Paris**.\n",
            "\n"
          ]
        }
      ],
      "execution_count": null
    },
    {
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "NHO9VzO9AHZP",
        "outputId": "f5667fab-a9f3-487f-cff1-5f5ac1549366"
      },
      "cell_type": "code",
      "source": [
        "# @title Choose a different model\n",
        "from google.colab import ai\n",
        "\n",
        "response = ai.generate_text(\"What is the capital of England\", model_name='google/gemini-2.0-flash-lite')\n",
        "print(response)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The capital of England is **London**.\n",
            "\n"
          ]
        }
      ],
      "execution_count": null
    },
    {
      "metadata": {
        "id": "ysDdFbH_Dgtz"
      },
      "cell_type": "markdown",
      "source": [
        "For longer text generations, you can stream the response. This displays the output token by token as it's generated, rather than waiting for the entire response to complete. This provides a more interactive and responsive experience. To enable this, simply set stream=True."
      ]
    },
    {
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "4BNgxiB6--_5",
        "outputId": "d3b34d85-1283-4226-861c-73ff431000f7"
      },
      "cell_type": "code",
      "source": [
        "# @title Simple streaming example\n",
        "from google.colab import ai\n",
        "\n",
        "stream = ai.generate_text(\"Tell me a short story.\", stream=True)\n",
        "for text in stream:\n",
        "  print(text, end='')"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The lighthouse keeper, Silas, was a man of routine. Every night, for fifty years, he'd lit the lamp, a beacon against the treacherous rocks that gnawed at the coastline. The sea was his companion, his enemy, and his only confidante. He knew its moods better than his own.\n",
            "\n",
            "One stormy night, the wind howled like a banshee. The waves crashed against the tower, shaking it to its core. Silas, clinging to the railing, felt a fear he hadn't experienced in decades. This wasn't just a storm; this was a monster.\n",
            "\n",
            "Suddenly, a small, wooden boat, tossed about like a toy, appeared in the raging sea. He squinted, his heart leaping into his throat. A child. Alone.\n",
            "\n",
            "Ignoring the raging tempest, Silas raced down the winding stairs, his old bones protesting with every step. He launched his small rescue boat, a fragile craft against the fury of the storm.\n",
            "\n",
            "Fighting the waves, he reached the child. A girl, no older than seven, clung to the wreckage, her face white with terror. With a strength born of desperation, Silas pulled her aboard.\n",
            "\n",
            "The journey back was a blur of wind, spray, and fear. The lighthouse seemed miles away, a distant pinprick of hope. But Silas held on, whispering words of comfort to the shivering child.\n",
            "\n",
            "Finally, they reached the safety of the tower. He wrapped her in blankets, fed her warm soup, and listened to her tale of a capsized fishing boat and a lost father.\n",
            "\n",
            "As the storm raged outside, the little girl slept, curled up in Silas's worn armchair. Looking at her, a profound shift occurred within him. For fifty years, he’d only kept the light burning. Now, he understood that the light wasn't just a warning. It was a hope, a guiding star. And he, Silas, was more than just a keeper of the light. He was a keeper of hope.\n",
            "\n",
            "The storm eventually subsided. The girl was reunited with her father, miraculously rescued from a nearby island. Silas, watching them embrace, felt a warmth he hadn't known he was missing. The sea remained, his companion and his enemy. But now, it was also a reminder of the girl he'd saved, and the profound understanding that even in the darkest storms, a single act of kindness could illuminate the world. And that, he knew, was a light worth keeping.\n"
          ]
        }
      ],
      "execution_count": null
    },
    {
      "metadata": {
        "id": "CpMmpaVClSBV",
        "cellView": "form"
      },
      "cell_type": "code",
      "source": [
        "#@title Text formatting setup\n",
        "#code is not necessary for colab.ai, but is useful in fomatting text chunks\n",
        "import sys\n",
        "\n",
        "class LineWrapper:\n",
        "    def __init__(self, max_length=80):\n",
        "        self.max_length = max_length\n",
        "        self.current_line_length = 0\n",
        "\n",
        "    def print(self, text_chunk):\n",
        "        i = 0\n",
        "        n = len(text_chunk)\n",
        "        while i < n:\n",
        "            start_index = i\n",
        "            while i < n and text_chunk[i] not in ' \\n': # Find end of word\n",
        "                i += 1\n",
        "            current_word = text_chunk[start_index:i]\n",
        "\n",
        "            delimiter = \"\"\n",
        "            if i < n: # If not end of chunk, we found a delimiter\n",
        "                delimiter = text_chunk[i]\n",
        "                i += 1 # Consume delimiter\n",
        "\n",
        "            if current_word:\n",
        "                needs_leading_space = (self.current_line_length > 0)\n",
        "\n",
        "                # Case 1: Word itself is too long for a line (must be broken)\n",
        "                if len(current_word) > self.max_length:\n",
        "                    if needs_leading_space: # Newline if current line has content\n",
        "                        sys.stdout.write('\\n')\n",
        "                        self.current_line_length = 0\n",
        "                    for char_val in current_word: # Break the long word\n",
        "                        if self.current_line_length >= self.max_length:\n",
        "                            sys.stdout.write('\\n')\n",
        "                            self.current_line_length = 0\n",
        "                        sys.stdout.write(char_val)\n",
        "                        self.current_line_length += 1\n",
        "                # Case 2: Word doesn't fit on current line (print on new line)\n",
        "                elif self.current_line_length + (1 if needs_leading_space else 0) + len(current_word) > self.max_length:\n",
        "                    sys.stdout.write('\\n')\n",
        "                    sys.stdout.write(current_word)\n",
        "                    self.current_line_length = len(current_word)\n",
        "                # Case 3: Word fits on current line\n",
        "                else:\n",
        "                    if needs_leading_space:\n",
        "                        # Define punctuation that should not have a leading space\n",
        "                        # when they form an entire \"word\" (token) following another word.\n",
        "                        no_leading_space_punctuation = {\n",
        "                            \",\", \".\", \";\", \":\", \"!\", \"?\",        # Standard sentence punctuation\n",
        "                            \")\", \"]\", \"}\",                     # Closing brackets\n",
        "                            \"'s\", \"'S\", \"'re\", \"'RE\", \"'ve\", \"'VE\", # Common contractions\n",
        "                            \"'m\", \"'M\", \"'ll\", \"'LL\", \"'d\", \"'D\",\n",
        "                            \"n't\", \"N'T\",\n",
        "                            \"...\", \"…\"                          # Ellipses\n",
        "                        }\n",
        "                        if current_word not in no_leading_space_punctuation:\n",
        "                            sys.stdout.write(' ')\n",
        "                            self.current_line_length += 1\n",
        "                    sys.stdout.write(current_word)\n",
        "                    self.current_line_length += len(current_word)\n",
        "\n",
        "            if delimiter == '\\n':\n",
        "                sys.stdout.write('\\n')\n",
        "                self.current_line_length = 0\n",
        "            elif delimiter == ' ':\n",
        "                # If line is full and a space delimiter arrives, it implies a wrap.\n",
        "                if self.current_line_length >= self.max_length:\n",
        "                    sys.stdout.write('\\n')\n",
        "                    self.current_line_length = 0\n",
        "\n",
        "        sys.stdout.flush()\n"
      ],
      "outputs": [],
      "execution_count": null
    },
    {
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DWiLPzTnRoy-",
        "outputId": "7a9f17e2-ebb4-4bd6-a140-6376235197fb"
      },
      "cell_type": "code",
      "source": [
        "# @title Formatted streaming example\n",
        "from google.colab import ai\n",
        "\n",
        "wrapper = LineWrapper()\n",
        "for chunk in ai.generate_text('Give me a long winded description about the evolution of the Roman Empire.', model_name='google/gemini-2.0-flash', stream=True):\n",
        "  wrapper.print(chunk)"
      ],
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Alright, settle in, because the Roman Empire’s evolution wasn't a tidy, linear\n",
            "process. It was a centuries-long, tumultuous transformation, marked by\n",
            "breathtaking innovation, brutal power struggles, and a slow, creeping societal\n",
            "decay. We're talking about a journey from a humble city-state in the Italian\n",
            "peninsula to a sprawling, multifaceted empire that left an indelible mark on\n",
            "law, language, architecture, governance, and even our very understanding of the\n",
            "world.\n",
            "\n",
            "It all began, as legend would have it, with Romulus and Remus, twin brothers\n",
            "raised by a she-wolf, who founded the city of Rome in 753 BCE. Now, that’s just\n",
            "a legend, but it serves to highlight the foundational spirit of Rome: ambition,\n",
            "strength, and a certain ruthlessness. Initially, Rome was ruled by a monarchy, a\n",
            "system eventually deemed unsatisfactory by the powerful patrician class. This\n",
            "led to the **Roman Republic**, established around 509 BCE, a watershed moment\n",
            "that would define the early character of Rome.\n",
            "\n",
            "The Republic was a complex system of checks and balances designed to prevent any\n",
            "one individual from gaining absolute power. It involved a Senate, composed of\n",
            "elder statesmen primarily drawn from the patrician class, who advised and\n",
            "controlled finances; elected officials, such as Cons uls (two elected heads of\n",
            "state who served one-year terms), Praetors (judges), and Quaestors (financial\n",
            "administrators); and popular assemblies where citizens could theoretically\n",
            "participate in governance.\n",
            "\n",
            "But the Republic wasn't a democracy in the modern sense. Power was largely\n",
            "concentrated in the hands of the wealthy aristocratic families, and while\n",
            "plebeians (the common citizens) eventually gained some representation through\n",
            "tribunes who could veto acts of the Senate, the system remained inherently\n",
            "biased.\n",
            "\n",
            "This period of the Republic was one of relentless expansion. Through a series of\n",
            "shrewd alliances and brutal wars, Rome gradually conquered its neighbors,\n",
            "including the Etruscans, the Samnites, and various other Italian tribes. These\n",
            "victories were crucial because they allowed Rome to control the Italian\n",
            "peninsula, providing it with manpower, resources, and a strategic advantage.\n",
            "\n",
            "The **Punic Wars** against Carthage, a powerful North African trading empire,\n",
            "were a defining moment. These protracted conflicts, especially the Second Punic\n",
            "War with Hannibal's legendary invasion of Italy, tested Rome's resilience to the\n",
            "absolute limit. The Roman resilience, coupled with tactical brilliance and\n",
            "strategic advantages, ultimately led to Carthage's complete destruction,\n",
            "establishing Rome as the dominant power in the Mediterranean.\n",
            "\n",
            "However, the very success of the Republic sowed the seeds of its eventual\n",
            "downfall. The influx of wealth and slaves from conquered territories created\n",
            "vast disparities in wealth. Powerful generals, enriched by conquest and\n",
            "commanding loyal armies, began to challenge the authority of the Senate.\n",
            "\n",
            "Figures like **Marius**, who revolutionized the Roman army by allowing landless\n",
            "citizens to enlist, creating a professional, loyal force, and **Sulla**, who\n",
            "marched on Rome with his army to seize power, demonstrated the fragility of the\n",
            "Republican system. This era saw a series of civil wars and political\n",
            "assassinations, further destabilizing the Republic.\n",
            "\n",
            "The **First Triumvirate**, an informal alliance between Julius Caesar, Pompey,\n",
            "and Crassus, was an attempt to stabilize the political landscape, but it\n",
            "ultimately collapsed due to ambition and rivalry. **Julius Caesar's** rise to\n",
            "power was perhaps the most dramatic turning point. He conquered Gaul, defied the\n",
            "Senate, crossed the Rubicon, and ultimately seized control of Rome as dictator\n",
            "perpet uo. His reforms, aimed at improving the lives of ordinary citizens and\n",
            "consolidating his power, were cut short by his assassination in 44 BCE.\n",
            "\n",
            "Caesar's assassination sparked another round of civil wars. The **Second\n",
            "Triumvirate**, comprised of Mark Antony, Octavian (Caesar's adopted son), and\n",
            "Lepidus, emerged to restore order. However, this alliance also disintegrated,\n",
            "leading to a power struggle between Antony and Octavian. Octavian's victory at\n",
            "the Battle of Actium in 31 BCE marked the definitive end of the Roman Republic.\n",
            "\n",
            "Octavian, now known as **Augustus **, carefully crafted a new political system.\n",
            "He avoided the title of \"king\" or \"dictator,\" instead adopting the title of\n",
            "\"Princeps,\" meaning \"first citizen.\" He maintained the facade of the Republic,\n",
            "keeping the Senate and other Republican institutions, but in reality, he held\n",
            "absolute power. This transition from Republic to Empire was a gradual process,\n",
            "cleverly disguised by Augustus. He restructured the army, reformed the tax\n",
            "system, initiated massive building projects, and ushered in a period of relative\n",
            "peace and prosperity known as the **Pax Romana** (Roman Peace).\n",
            "\n",
            "The Julio-Claudian dynasty, which followed Augustus, saw a mixed bag of\n",
            "emperors. Tiberius was a capable administrator but reclusive, Caligula was\n",
            "notorious for his cruelty and extravagance, Claudius was an intellectual who\n",
            "expanded the Empire, and Nero was infamous for his alleged role in the Great\n",
            "Fire of Rome and his persecution of Christians.\n",
            "\n",
            "The year 69 CE, known as the ** Year of the Four Emperors**, revealed the\n",
            "instability of the imperial succession. After Nero's death, four different\n",
            "emperors claimed the throne in rapid succession, highlighting the power of the\n",
            "army to make and break emperors.\n",
            "\n",
            "The Flavian dynasty, established by Vespasian, brought stability and marked the\n",
            "beginning of the construction of the Col osseum. The Nerva-Antonine dynasty,\n",
            "often considered the \"Five Good Emperors\" (Nerva, Trajan, Hadrian, Antoninus\n",
            "Pius, Marcus Aurelius), saw the Roman Empire reach its greatest territorial\n",
            "extent and experience a period of unprecedented peace and prosperity.\n",
            "\n",
            "Trajan conquered Dacia (modern Romania) and expanded the Empire into\n",
            "Mesopotamia, while Hadrian focused on consolidating the Empire's borders and\n",
            "building defensive fortifications like Hadrian's Wall in Britain. Marcus\n",
            "Aurelius, a philosopher-king, faced constant warfare on the frontiers and wrote\n",
            "his famous \"Meditations.\"\n",
            "\n",
            "The reign of Commodus, the son of Marcus Aurelius, marked a turning point. His\n",
            "erratic behavior and autocratic rule undermined the stability of the Empire and\n",
            "foreshadowed future troubles. The Severan dynasty, which followed, saw the rise\n",
            "of powerful military emperors who relied heavily on the army for support. This\n",
            "increased military influence further weakened the Senate and other civilian\n",
            "institutions.\n",
            "\n",
            "The 3rd century CE was a period of profound crisis. The **Crisis of the Third\n",
            "Century** was characterized by constant civil wars, barbarian invasions,\n",
            "economic decline, and plague. The Empire was divided into competing factions,\n",
            "and emperors rose and fell in rapid succession.\n",
            "\n",
            "Emperor Diocletian attempted to stabilize the Empire by dividing it into two\n",
            "halves, the Western Roman Empire and the Eastern Roman Empire (later known as\n",
            "the Byzantine Empire), each ruled by an Augustus and a Caesar. This tetrarchy, a\n",
            "system of four rulers, aimed to provide more effective governance and defense.\n",
            "\n",
            "Constantine I, also known as Constantine the Great, reunited the Empire and made\n",
            "Christianity the favored religion with the Edict of Milan in 313 CE. He also\n",
            "moved the capital from Rome to Byzantium, renaming it Constantinople. This shift\n",
            "reflected the growing importance of the Eastern provinces and the weakening of\n",
            "the Western Empire.\n",
            "\n",
            "Following Constantine's death, the Empire was again divided between his sons.\n",
            "The Western Roman Empire continued to decline, plagued by internal strife,\n",
            "economic problems, and constant barbarian invasions. The Eastern Roman Empire,\n",
            "with its stronger economy and more stable political system, managed to survive.\n",
            "\n",
            "The **Visigoths**, fleeing from the Huns, were allowed to settle within the\n",
            "Roman Empire, but their mistreatment by Roman officials led to rebellion. In 410\n",
            "CE, the Visigoths sacked Rome, a symbolic blow that shook the foundations of the\n",
            "Western Roman Empire.\n",
            "\n",
            "One by one, provinces of the Western Roman Empire were lost to various barbarian\n",
            "tribes, including the Vandals, the Franks, the Angles, and the Saxons. In 476\n",
            "CE, the last Western Roman Emperor, Romulus Augustulus, was deposed by the\n",
            "Germanic chieftain Odoacer, marking the traditional end of the Western Roman\n",
            "Empire.\n",
            "\n",
            "The Eastern Roman Empire, or Byzantine Empire, continued to flourish for another\n",
            "thousand years, preserving Roman traditions and culture. It would eventually\n",
            "fall to the Ottoman Turks in 1453, with the capture of Constantinople.\n",
            "\n",
            "So, the evolution of the Roman Empire was a complex and multifaceted process,\n",
            "spanning centuries and encompassing profound political, social, economic, and\n",
            "cultural transformations. From a small Republic to a vast empire, and eventually\n",
            "to a fragmented and weakened state, the Roman story is a testament to the rise\n",
            "and fall of civilizations, the enduring power of ideas, and the enduring legacy\n",
            "of one of history's most influential empires. It's a story of ambition,\n",
            "innovation, ruthlessness, and ultimately, decline – a cautionary tale and a\n",
            "source of inspiration that continues to fascinate and influence us today.\n",
            "\n"
          ]
        }
      ],
      "execution_count": null
    }
  ],
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
